<?php
/**
 * @property $id int 
 */
abstract class Core_Model_Category extends YouNet_Db_Table_Row
{
	public function getName()
	{
		$view = Zend_Layout::getMvcInstance()->getView();
		$this->name = $view->escape($this->name);
		$this->name = str_replace(array('&quot;', '&amp;'), array('"', '&'), $this->name);
		return $this->name;
	}
	/**
	 *
	 * @return Core_Model_Cateogry
	 */
	public function getParentCategory()
	{
		$parentCategory = $this->getTable()->findOne($this->id_parent);
		return $parentCategory;
	}
	
	public function hasParentCategory()
	{
		return !empty($this->id_parent);
	}
	
	public function hasChildCategory()
	{
		return $this->getTable()->fetchAll(array('id_parent = ?' => $this->id))->count() > 0;
	}
	
	/**
	 *
	 * @return Zend_Db_Table_Rowset
	 */
	public function getChildrentCategories()
	{
		return $this->getTable()->fetchAll(array(
			'id_parent' => $this->id
		));
	}
    public function increaseActiveProductNumbers()
    {
        $this->number_active_products += 1;
        $this->save();
        return $this;
    }
    public function decreaseActiveProductNumbers()
    {
        $this->number_active_products -= 1;
        $this->save();
        return $this;
    }	
	public function increaseTotalProductNumbers()
	{
        $this->number_products += 1;            
		$this->save();
		return $this;
	}		
    public function decreaseTotalProductNumbers()
	{
		$this->number_products -= 1;        
		$this->save();
		return $this;
	}
	
	public function getHierarchyIdCategories()
	{
		$arrIdCategories	= array();
		if( $this->path )
		{
			$arrIdCategories = explode(Core_Model_DbTable_Category_Abstract::DELIMITER, substr($this->path, 0, -1));
		}
		else
		{
			$arrIdCategories[]	= $this->id;
			$parent				= $this->getParentCategory(); 
			while( !empty($parent->id) )
			{
				$arrIdCategories[]	= $parent->id;
				$parent				= $parent->getParentCategory();
			}
			$arrIdCategories = array_reverse($arrIdCategories);
		}
		return $arrIdCategories;
	}
	
	/**
	 *
	 * @param boolean $is_decrease_total_product
	 * true: decrease both number product and number active products
	 * false: only decrease number active products
	 * @return Core_Model_Category 
	 */
	public function decreaseActiveProduct($is_decrease_total_product = true)
	{

		if ($is_decrease_total_product)
		{
			$this->decreaseTotalProductNumbers();
		}
		else
		{
			$this->number_active_products -= 1;
			$this->save();
		}
		return $this;
	}
	
	public function getNumberActiveProducts()
	{
		return $this->number_active_products;
	}
	
	public function getNumberTotalProducts()
	{
		return $this->number_products;
	}
	
	public function canDelete()
	{
		if( $this->getNumberTotalProducts()
			|| $this->hasChildCategory()
		)
		{
			return false;
		}
		return true;
	}
}